## Viasat (Play) have an API but it isn't for public use
module Shin
  module Play
    class Viasat
      
      def new
        self
      end
      
      # Videos
      def videos(params={})
        # Response
        response = Base.get('http://playapi.mtgx.tv/v3/videos?' + URI.encode_www_form(params))
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Return this
        ret = {page: nil, total_pages: nil, results: []}

        # Data
        data = Oj.load(response.body) rescue nil
        
        # Can't be nil
        if data != nil
          ret[:page] = data['count']['page'].to_i
          ret[:total_pages] = data['count']['total_pages'].to_i
          ret[:results] = data["_embedded"]['videos']
          
          ret.to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end
        
      end
      
      # Channels
      def channels(params={})
        params[:page] ||= 1
        
        # Response
        response = Base.get('http://playapi.mtgx.tv/v3/channels?' + URI.encode_www_form(params))
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Return this
        ret = {page: nil, total_pages: nil, results: []}

        # Data
        data = Oj.load(response.body) rescue nil
        
        # Can't be nil
        if data != nil
          ret[:page] = data['count']['page'].to_i
          ret[:total_pages] = data['count']['total_pages'].to_i
          ret[:results] = data["_embedded"]['channels']
          
          ret.to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end

      end
      
      # Video
      def video(params={})
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""
        
        # Response
        response = Base.get('http://playapi.mtgx.tv/v3/videos/' + params[:id].to_s)
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Data
        data = Oj.load(response.body) rescue nil
        
        # Can't be nil
        if data != nil
          data.to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end
      end
      
      # Errors
      class NotValid         < StandardError; end
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end